/**
 * @controller 用户 users
 */
const Controller = require('egg').Controller;
const NodeRSA = require('node-rsa');
class UserController extends Controller{
  /**
   * @summary 获取用户
   * @description 获取用户
   * @request query string username 用户名
   * @request query string keyword 用户名/邮箱/手机号
   * @request query string email 邮箱
   * @request query string phone 手机号
   * @request query query number state 状态
   * @request query number department_id 部门ID
   * @request query number limit limit
   * @request query number offset offset
   * @router get /api/v1/users/list
   */
  async findAll() {
    const { ctx, service } = this;
    ctx.validate(ctx.rule.userListBodyReq, ctx.query);
    const res = await service.users.findAll(ctx.query);
    ctx.helper.body.SUCCESS({ ctx, res });
  }
	/**
	 * @summary 注册
	 * @description 注册
	 * @router post /api/v1/users
	 * @request body userCreateBodyReq
	 */
  async create() {
    const { ctx, service } = this;
    const params = {
      ...ctx.rule.userCreateBodyReq,
      verification_type: {
        type: 'enum',
        values: [1, 2],
      },
    };
    ctx.validate(params, ctx.request.body);
    const res = await service.users.create(ctx.request.body);
    if (!res.__code_wrong) {
      ctx.helper.body.CREATED_UPDATE({ ctx });
    } else {
      ctx.helper.body.INVALID_REQUEST({ ctx, code: res.__code_wrong, msg: res.message });
    }
	}
  /** 
   * @summary 登录
   * @description 登录
   * @router post /api/v1/users/login
   * @requst body userBodyReq
   */
  async login(){
    const { ctx, service, app } = this;
    const params = {
      username: ctx.rule.userBodyReq.username,
      password: ctx.rule.userBodyReq.password,
    };
    ctx.validate(params, ctx.request.body);
    // 如果不是开发环境 获取配置中的rsa私钥对密码解密
    if (app.config.env === 'prod') {
      try {
        const { rsa_private_key } = await ctx.model.Configurations.findOne({
          where: { id: 1 },
        });
        const key = new NodeRSA(rsa_private_key);
        ctx.request.body.password = key.decrypt(ctx.request.body.password, 'utf8');
      } catch (e) {
        ctx.helper.body.UNAUTHORIZED({ ctx });
        return app.logger.errorAndSentry(e);
      }
    }
    ctx.validate(params, ctx.request.body);
    const res = await service.users.login(ctx.request.body)
    switch (res.__code_wrong) {
      case undefined:
        ctx.helper.body.SUCCESS({ ctx, res });
        break;
      case 40000:
        ctx.helper.body.INVALID_REQUEST({ ctx, code: 40000, msg: '密码错误' });
        break;
      case 40004:
        ctx.helper.body.INVALID_REQUEST({
          ctx,
          code: 40004,
          msg: '用户不存在',
        });
        break;
      case 40005:
        ctx.helper.body.INVALID_REQUEST({
          ctx,
          code: 40005,
          msg: '账号已停用',
        });
        break;
      default:
        ctx.helper.body.UNAUTHORIZED({ ctx });
        break;
    }
  }
  /** 
   * @summary 获取用户信息
   * @description 获取用户信息
   * @router get /api/v1/users/user_info
    */
   async userInfo(){
    const { ctx, service } = this;
    const res = await service.users.userInfo();
    res ? ctx.helper.body.SUCCESS({ ctx, res }) : ctx.helper.body.NOT_FOUND({ctx});
   }
     /**
   * @summary 刷新token
   * @description 刷新token
   * @router post /api/v1/users/refreshToken
   */
  async refreshToken() {
    const { ctx, app, service } = this;
    const params = {
      refreshToken: {
        type: 'string',
        required: true,
        trim: true,
        example: '',
        description: 'refreshToken',
      },
      secret: {
        type: 'string',
        required: true,
        trim: true,
        example: '',
        description: '秘钥',
      },
    };
    ctx.validate(params, ctx.request.body);
    // 如果验证方式是jwt，否则为session
    if (app.config.verification_mode === 'jwt') {
      const res = await service.users.refreshToken(ctx.request.body);
      switch (res.__code_wrong) {
        case undefined:
          ctx.helper.body.SUCCESS({ ctx, res });
          break;
        case 40000:
        case 40001:
        case 40002:
        case 40003:
          ctx.helper.body.INVALID_REQUEST({ ctx, code: res.__code_wrong, msg: res.message });
          break;
        default:
          ctx.helper.body.INVALID_REQUEST({ ctx });
          break;
      }
    } else {
      ctx.helper.body.INVALID_REQUEST({ ctx });
    }
  }
  /**
   * @summary 获取 是否存在此用户字段
   * @description 获取 是否存在此用户字段
   * @router get /api/v1/users/exists_user_unique_fields
   */
  async existsUserUniqueFields() {
    const { ctx, service } = this;
    const params = {
      username: {
        ...ctx.rule.userBodyReq.username,
        required: false,
      },
      nickname: {
        ...ctx.rule.userBodyReq.nickname,
        required: false,
      },
      email: {
        ...ctx.rule.userBodyReq.email,
        required: false,
      },
      phone: {
        ...ctx.rule.userBodyReq.phone,
        required: false,
      },
    };
    ctx.validate(params, ctx.query);
    const res = await service.users.existsUserUniqueFields(ctx.query);
    res ? ctx.helper.body.SUCCESS({ ctx }) : ctx.helper.body.NOT_FOUND({ ctx });
  }
}

module.exports = UserController;
